const express = require('express');
const router = express.Router();
const { Course, Category, Chapter, User } = require('../../models');
const { NotFound, Forbidden } = require('http-errors');
const { success, failure } = require('../../utils/responses');

/**
 * 查询章节详情
 * GET /chapters/:id
 */
router.get('/:id', async function (req, res) {
  try {
    const { id } = req.params;
    const condition = {
      attributes: { exclude: ['CourseId'] },
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'name'],
          include: [
            {
              model: User,
              as: 'user',
              attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
            },
          ],
        },
      ],
    };

    const chapter = await Chapter.findByPk(id, condition);

    if (!chapter) {
      throw new NotFound(`ID: ${id}的章节未找到。`);
    }
    // 检查用户是否能浏览当前章节
    await checkUserRole(req, chapter);

    // 同属一个课程的所有章节
    const chapters = await Chapter.findAll({
      attributes: { exclude: ['CourseId', 'content'] },
      where: { courseId: chapter.courseId },
      order: [
        ['rank', 'ASC'],
        ['id', 'DESC'],
      ],
    });
    success({ res, message: '查询章节成功。', data: { chapter, chapters } });
  } catch (error) {
    failure({ res, error });
  }
});
/**
 * 检查用户是否能浏览当前章节
 * @param req
 * @param chapter
 * @returns {Promise<void>}
 */
async function checkUserRole(req, chapter) {
  // 如果章节是免费的
  if (chapter.free) {
    return;
  }

  // 检查用户是否有权限访收费章节
  const allowedRoles = [1, 100]; // 大会员和管理员的角色ID
  const user = await User.findByPk(req.userId);
  if (!allowedRoles.includes(user.role)) {
    throw new Forbidden('您没有权限浏览，请先购买大会员后再访问。');
  }
}

module.exports = router;
